<?php

namespace App\Services;

use App\Models\CartItem;
use App\Models\User;

class CartService {
    
    public function add($product_sku_id, $amount)
    {
        $user = request()->user();
        // 获取我的购物车
        if ($porduct_sku = $user->cartItems()->where('product_sku_id', $product_sku_id)->first()) {

            // 更新购物车
            $porduct_sku->update([
                'amount' => $porduct_sku->amount + $amount
            ]);

        } else {

            // 给购物车新增一条记录
            $cartItem = new CartItem([
                'amount' => $amount,
            ]);
            $cartItem->user()->associate($user);
            $cartItem->productSku()->associate($product_sku_id);
            $cartItem->save();
        }

        return true;
    }

    public function edit($product_sku_id, $amount)
    {
        $user = request()->user();
        // 获取我的购物车
        if ($porduct_sku = $user->cartItems()->where('product_sku_id', $product_sku_id)->first()) {

            // 更新购物车
            $porduct_sku->update([
                'amount' => $amount
            ]);

        } else {

            // 给购物车新增一条记录
            $cartItem = new CartItem([
                'amount' => $amount,
            ]);
            $cartItem->user()->associate($user);
            $cartItem->productSku()->associate($product_sku_id);
            $cartItem->save();
        }

        return true;
    }

    public function get()
    {
        return request()->user()->cartItems()->with(['productSku.product'])->get();
    }

    /**
     * 移除购物车商品
     * @param $skuIds
     */
    public function remove($skuIds, $user_id = 0)
    {
        if (!is_array($skuIds)) {
            $skuIds = [$skuIds];
        }
        if ($user_id) {
            User::query()->find($user_id)->cartItems()->whereIn('product_sku_id', $skuIds)->delete();
        } else {
            request()->user()->cartItems()->whereIn('product_sku_id', $skuIds)->delete();
        }

    }

    /**
     * 获取购物车商品数量
     * @return mixed
     */
    public function count()
    {
        return request()->user()->cartItems()->count();
    }
}